<?php


namespace app\utils;

#快速注册企业小程序
# https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/Register_Mini_Programs/Fast_Registration_Interface_document.html
use think\facade\Cache;
use think\facade\Db;

class WeixinApp
{
    public static function getMid(){
        global $user;
        if(!empty($user->mall_id)){
            $mid=$user->mall_id;
        }else{
            $mid=request()->header('mid');
        }
        return $mid;
    }
    public static function getConfig(){
        $mid=self::getMid();
        $config = Db::table('jiecheng_configuration')
            ->where('type', 'WeixinApp')
            ->where('mall_id', $mid)
            ->value('configuration');
        $config = json_decode($config, true);
        return $config;
    }
    /**
     * 创建小程序接口
     */
    public static function create($data)
    {
        $token = self::getComponentToken();

        $result = wx_request('post', 'https://api.weixin.qq.com/cgi-bin/component/fastregisterweapp?action=create&component_access_token=' . $token, $data);
        return $result;
    }

    public static function getComponentToken()
    {
        $config=self::getConfig();
        $appid=$config['appid'] ?? '';

        $component_access_token=Cache::get("component_access_token:".$appid);
        if (empty($component_access_token)){
            $d = Cache::get("wechat_verifyticket:".$appid);
            if (empty($d)) {
                throw new \Exception("无有效ticket", HTTP_NOTACCEPT);
            }
            $data['component_verify_ticket'] = $d['component_verify_ticket'] ?? '';
            $data['component_appid'] = $config['appid'] ?? '';//"wx3d6fb6b574ab63fe";
            $data['component_appsecret'] = $config['appsecret'] ?? '';//"104fab88c02ed28a1301a0f720b4e39e";
            $result = wx_request('post', 'https://api.weixin.qq.com/cgi-bin/component/api_component_token', $data,
                [
                    'Content-Type' => 'application/json'
                ]
            );
            if (empty($result['component_access_token'])){
                $errmsg=$result['errmsg'] ?? '';
                throw new \Exception("获取component_access_token失败".$errmsg, HTTP_NOTACCEPT);
            }
            Cache::set("component_access_token:".$appid,$result['component_access_token'],60*60);
            return $result['component_access_token'];
        }
        return $component_access_token;
    }
}